<?php
class validate extends CS_Controller
{
    public function _init()
    {
        $this->load->helper('common');
        $this->load->helper('email');
        $this->load->model('user_model', 'user');
        $this->load->model('user_code_model', 'user_code');
        $this->load->model('getpwd_phone_model', 'getpwd_phone');
        $this->load->model('getpwd_email_model', 'getpwd_email');
        $this->load->model('user_related_self_model','user_related_self');
    }

    public function modifyPw()
    {
        $userInfo = $this->user->findByUid($this->uid)->row();
        if ( empty($userInfo->mobile_phone) ){
            $this->success('validate/bindingPhone', null, '请先绑定手机');
        }
        $data['userInfo'] = $userInfo;
        $this->load->view('validate/modifyPw', $data);
    }

    public function modifyPwAction()
    {
        $captcha = $this->input->post('mobilePhoneCaptcha');
        $userInfo = $this->user->findByUid($this->uid)->row();
        if ( empty($userInfo->mobile_phone) ){
            $this->error('validate/bindingPhone', null, '请先绑定手机');
        }
        $error = get_cookie('error');
        if (!isset($captcha) || strlen($captcha) != 6) {
            $this->ajaxJson(false, '请输入正确的手机验证码');
        }
        $endTime = date('Y-m-d H:i:s');
        $result = $this->user_code->findOne(['mobile' => $userInfo->mobile_phone, 'code' => $captcha], 'id, end_time');//, 'end_time' => $endTime
        if ($result->num_rows() <= 0) {
            set_cookie('error', $error + 1, 43200);
            $this->ajaxJson(false, '手机验证码错误');
        }
        if ($result->row(0)->end_time < $endTime) {
            $this->ajaxJson(false, '手机验证码超过有效期，请重新获取~');
        }
        $this->ajaxJson(true, site_url('validate/modifyPwActionView'));
        
    }

    public function modifyPwActionView()
    {
        $this->load->view('validate/modifyPwAction');
    }
    
    public function modifyPwSuccess()
    {
        if ($this->input->post('password') != $this->input->post('confirmPassword')) {
            $this->error('validate/modifyPwActionView', '', '2次密码不一致');
        }
        
        if (strlen($this->input->post('password')) < 6) {
            $this->error('validate/modifyPwActionView', '', '密码长度必须大于6位');
        }
        $postData = $this->input->post();
        $postData['uid'] = $this->uid;
        $update = $this->user->modifyPassword($postData);

        if (!$update) {
            $this->error('validate/modifyPwActionView', '', '密码修改失败');
        }
        $this->load->view('validate/modifyPwSuccess');
    }
    

    public function modifyMail()
    {
        $userInfo = $this->user->findByUid($this->uid)->row();
        if ( !$userInfo->mobile_phone ){
            $this->success('validate/bindingPhone', null, '请先绑定手机');
        }
        $data['userInfo'] = $userInfo;
        $this->load->view('validate/modifyMail', $data);
    }

    public function modifyMailAction()
    {
        if ( !$this->session->flashdata('error') ) {
            $captcha = $this->input->post('mobilePhoneCaptcha');
            if ( empty($captcha) ) {
                $this->error('validate/modifyMail', null, '请输入手机验证码');
            }
            $userInfo = $this->user->findByUid($this->uid)->row();
            $result = $this->getpwd_phone->validatePhone(array('mobile_phone'=> $userInfo->mobile_phone, 'verify' => $captcha ,'flag' => 1), true);
            if ( $result->num_rows() == 0 ) {
                $this->error('validate/modifyMail', null, '您输入的手机验证码不正确');
            }
            $this->getpwd_phone->updateFlag($result->row()->id);
        }
        $data['captcha'] = $this->getCaptcha(18, 100, 27, 5);
        $this->load->view('validate/modifyMailAction', $data);
    }

    public function modifyMailCheck()
    {
        $email = $this->input->post('email');
        if ( !valid_email($email) ) {
            $this->error('validate/modifyMailAction', null, '请输入正确的邮箱地址');
        }
        if (strtolower($this->input->post('captcha')) != strtolower(get_cookie('captcha'))) {
            $this->error('validate/modifyMailAction', null, '请输入正确的验证码');
        }
        $uniqueCode = md5(sha1(uniqid(). mt_rand(1000,9999)));
        $urlQueryString =  'type1=emd&type2=start&action=' . urlencode(base64_encode($uniqueCode));
        $sendMessage = '尊敬的 '.$this->userName .' 您好：您于 '. date('Y年m月d日 H时i分s秒') .' 申请验证邮箱，点击以下按钮，即可完成验证：'
            . site_url('validate/modifyMailSuccess') . '?' . ($urlQueryString);

        $result = $this->getpwd_email->findByUserName(array('username'=> $this->userName, 'email' => $email));
        if ( $result->num_rows() > 0 ) {
            $flag = $this->getpwd_email->updateCode(array('username'=> $this->userName, 'email' => $email,'cdkey'=>$uniqueCode));
        } else {
            $flag = $this->getpwd_email->insertInto(array('username'=> $this->userName, 'email' => $email,'cdkey'=>$uniqueCode));
        }
        $send = sendEmails($email, '着想科技网邮箱验证提醒', $sendMessage);
        if ( !$flag || !$send ) {
            $this->error('validate/modifyMailAction', null, '邮箱发送失败');
        }

        $data['email'] = $email;
        $data['mailUrl'] = 'http://mail.'. substr(strstr($email, '@'), 1); //截取什么发送的邮箱
        $this->load->view('validate/modifyMailCheck', $data);
    }

    public function modifyMailSuccess()
    {
        $action = $this->input->get('action');
        $result = $this->getpwd_email->verifyTheExistence($this->userName, base64_decode($action));
        if ( $result->num_rows() <= 0 ) {
            $this->error('validate/modifyMailAction', null, '抱歉，验证失败');
        }
        $row = $result->row();
        $this->db->trans_start();
        $flag = $this->getpwd_email->updateFlag($this->userName);
        $updateStatus = $this->user->updateUser($this->uid, array('user_email' => $row->email));
        $this->db->trans_complete();
        if ( $this->db->trans_status() === FALSE){
            $this->error('validate/modifyMailAction', null, '邮箱发送失败');
        }
        $this->load->view('validate/modifyMailSuccess');
    }

    public function modifyPhone()
    {
        $userInfo = $this->user->findByUid($this->uid)->row();
        if ( !$userInfo->mobile_phone ){
            $this->success('validate/bindingPhone', null, '请先绑定手机');
        }
        $data['userInfo'] = $userInfo;
        $this->load->view('validate/modifyPhone', $data);
    }

    public function modifyPhoneAction()
    {
        if ( !$this->session->flashdata('error') ) {
            $captcha = $this->input->post('mobilePhoneCaptcha');
            if (!isset($captcha) || strlen($captcha) != 6) {
                $this->error('validate/modifyPhone', null, '请输入正确的手机验证码');
            }
            $userInfo = $this->user->findByUid($this->uid)->row();
            $endTime = date('Y-m-d H:i:s');
            $result = $this->user_code->findOne(['mobile' => $userInfo->mobile_phone, 'code' => $captcha], 'id, end_time');
            if ($result->num_rows() <= 0) {
                $this->error('validate/modifyPhone', null, '您输入的手机验证码不正确');
            }
            if ($result->row(0)->end_time < $endTime) {
                $this->error('validate/modifyPhone', null, '手机验证码超过有效期，请重新获取~');
            }
        }
        $data['captcha'] = $this->getCaptcha(18, 100, 27, 5);
        $this->load->view('validate/modifyPhoneAction',$data);
    }

    public function modifyPhoneSuccess()
    {
        $mobilePhone = $this->input->post('mobilePhone');
        if ( !valid_mobile($mobilePhone) ) {
            $this->error('validate/modifyPhoneAction', null, '新输入的手机号码格式有误');
        }

        if (strtolower($this->input->post('captcha')) != strtolower(get_cookie('captcha'))) {
            $this->error('validate/modifyPhoneAction', null, '请输入正确的验证码');
        }
        $captcha = $this->input->post('mobilePhoneCaptcha');
        if ( empty($captcha) ) {
            $this->error('validate/modifyPhoneAction', null, '请输入手机验证码');
        }
        $userInfo = $this->user->findByUid($this->uid)->row();
        $endTime = date('Y-m-d H:i:s');
        $result = $this->user_code->findOne(['mobile' => $mobilePhone, 'code' => $captcha], 'id, end_time');
        if ( $result->num_rows() == 0 ) {
            $this->error('validate/modifyPhoneAction', null, '您输入的手机验证码不正确');
        }
        if ($result->row(0)->end_time < $endTime) {
            $this->error('validate/modifyPhoneAction', null, '手机验证码超过有效期，请重新获取~');
        }
        $this->user->updateUser($this->uid, array('mobile_phone' => $mobilePhone));
        $this->load->view('validate/modifyPhoneSuccess');
    }

    /**
     * 绑定手机
     */
    public function bindingPhone()
    {
        $userInfo = $this->user->findByUid($this->uid)->row();
        if ( $userInfo->mobile_phone ){
            $this->success('validate/modifyPhone', null, '手机已经绑定');
        }
        $data['captcha'] = $this->getCaptcha(18, 100, 27, 5);
        $this->load->view('validate/bindingPhone', $data);
    }

    public function bindingPhoneSuccess()
    {
        $mobilePhone = $this->input->post('mobilePhone');
        if ( !valid_mobile($mobilePhone) ) {
            $this->error('validate/bindingPhone', null, '新输入的手机号码格式有误');
        }

        if (strtolower($this->input->post('captcha')) != strtolower(get_cookie('captcha'))) {
            $this->error('validate/bindingPhone', null, '请输入正确的验证码');
        }
        $captcha = $this->input->post('mobilePhoneCaptcha');
        if ( empty($captcha) ) {
            $this->error('validate/bindingPhone', null, '请输入手机验证码');
        }
        $endTime = date('Y-m-d H:i:s');
        $result = $this->user_code->findOne(['mobile' => $mobilePhone, 'code' => $captcha], 'id, end_time');
        if ( $result->num_rows() == 0 ) {
            $this->error('validate/bindingPhone', null, '您输入的手机验证码不正确');
        }
        if ($result->row(0)->end_time < $endTime) {
            $this->error('validate/bindingPhone', null, '手机验证码超过有效期，请重新获取~');
        }
        $this->user->updateUser($this->uid, array('mobile_phone' => $mobilePhone));
        $this->load->view('validate/bindingPhoneSuccess');
    }

    public function modifySeller()
    {
        $userInfo = $this->user->findByUid($this->uid)->row();
        if ( empty($userInfo->mobile_phone) ){
            $this->success('validate/bindingPhone', null, '请先绑定手机');
        }
        $data['userInfo'] = $userInfo;
        $this->load->view('validate/modifySeller', $data);
    }
    
    public function modifySellerAction()
    {
        $captcha = $this->input->post('mobilePhoneCaptcha');
        $userInfo = $this->user->findByUid($this->uid)->row();
        if ( empty($userInfo->mobile_phone) ){
            $this->error('validate/bindingPhone', null, '请先绑定手机');
        }
        $error = get_cookie('error');
        if (!isset($captcha) || strlen($captcha) != 6) {
            $this->ajaxJson(false, '请输入正确的手机验证码');
        }
        $endTime = date('Y-m-d H:i:s');
        $result = $this->user_code->findOne(['mobile' => $userInfo->mobile_phone, 'code' => $captcha], 'id, end_time');//, 'end_time' => $endTime
        if ($result->num_rows() <= 0) {
            set_cookie('error', $error + 1, 43200);
            $this->ajaxJson(false, '手机验证码错误');
        }
        if ($result->row(0)->end_time < $endTime) {
            $this->ajaxJson(false, '手机验证码超过有效期，请重新获取~');
        }
        $this->ajaxJson(true, site_url('validate/modifySellerActionView'));
    }
    
    public function modifySellerActionView()
    {
        $res = $this->user_related_self->findOne(['provider_uid' => $this->uid]);
        $data = array();
        if ($res->num_rows() > 0) {
            $seller = $res->row();
            $res1 = $this->user->findOne(['uid' => $seller->reseller_uid]);
            $data['seller_id'] = $seller->reseller_uid;
            $data['seller_name'] = $res1->row()->user_name;
        }
        $this->load->view('validate/modifySellerAction',$data);
    }
    
    public function modifySellerSuccess()
    {
        $postData = $this->input->post();
        if (empty($postData['seller_id'])) {
            $this->ajaxJson(false, '请填写正确的分销商用户名或手机号');
        }
        $userRes = $this->user->findOne(['uid' => $postData['seller_id'],'user_type &4096=' => 4096]);
        if ($userRes->num_rows() <= 0){
            $this->ajaxJson(false, '用户不存在或不是分销商');
        }
        $res = $this->user_related_self->findOne(['provider_uid' => $this->uid]);
        $created_at = date('Y-m-d H:i:s');
        if ($res->num_rows() <= 0) {
            $is_suc = $this->user_related_self->insert(['provider_uid' => $this->uid, 'reseller_uid' => $postData['seller_id'], 'created_at' => $created_at]);
        }else {
            $is_suc = $this->user_related_self->update(['reseller_uid' => $postData['seller_id']],['provider_uid' => $this->uid]);
        }
        if (!$is_suc) {
            $this->ajaxJson(false, '修改分销商失败');
        }
        $this->ajaxJson(true, site_url('validate/modifySellerActionSuccessView'));
    }
    
    public function modifySellerActionSuccessView()
    {
        $this->load->view('validate/modifySellerActionSuccess');
    }
    
    /**
     * 发送短信
     */
    public function ajaxSendMessage()
    {
        $result = $this->user->findByUid($this->uid);
        if ( $result->num_rows() <= 0 ) {
            $this->ajaxJson(false,'用户没有登录，请从新登录。');
        }
        $phone = $result->row()->mobile_phone;
        if ( !valid_mobile($phone) ) {
            $this->ajaxJson(false,'手机号码格式有误或没有绑定号码');
        }
        $user = $this->user->validateMobilePhone(array('mobile_phone'=>$phone, 'uid' => $this->uid));
        if ( $user->num_rows() > 0 ) {
            $this->ajaxJson(false,'手机号码已绑定');
        }
        $this->sendCommonSms($phone, 'SMS_135430020');
    }

    public function sendMessage()
    {
        $phone = $this->input->post('mobilePhone');
        if ( !valid_mobile($phone) ) {
            $this->ajaxJson(false,'手机号码格式有误或没有绑定号码。');
        }

        $user = $this->user->validateMobilePhone(array('mobile_phone'=>$phone, 'uid' => $this->uid));
        if ( $user->num_rows() > 0 ) {
            $this->ajaxJson(false,'手机号码已绑定');
        }
        $this->sendCommonSms($phone, 'SMS_135430020');
    }

    /**
     * 发送短信
     */
    public function ajaxSendCaptcha()
    {
        $phone = $this->input->post('mobilePhone');
        if ( !valid_mobile($phone) ) {
            $this->ajaxJson(false,'手机号码格式有误');
        }
        $this->sendCommonSms($phone, 'SMS_135430020');
    }


    /**
     * 验证码
     */
    public function ajaxJsonCaptcha()
    {
        $captcha = $this->getCaptcha(18, 100, 27, 5);
        echo json_encode($captcha);exit;
    }

    /**
     * 验证分销商
     */
    public function ajaxQueryId()
    {
        $namephone = $this->input->post('namephone');
        if (valid_mobile($namephone)){
            $res = $this->user->findOne(['mobile_phone' => $namephone]);
            if ($res->num_rows() != 1){
                $this->ajaxJson(['status' => false, 'msg' => '用户不存在或存在多条']);
            }
        }else {
            $res = $this->user->findOne(['user_name' => $namephone]);
            if ($res->num_rows() != 1){
                $this->ajaxJson(['status' => false, 'msg' => '用户不存在或存在多条']);
            }
        }
        $id = $res->row()->uid;
        $this->ajaxJson(true,'',['id' => $id]);
    }
}